package com.eidos.blogs.common.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author ： Eidos
 * @date ：Created in 2021/1/19
 * @description：
 * @modified By：
 * @version: 1.0
 */

public class AsyncMapperTask<T> implements Runnable {
    Logger logger = LoggerFactory.getLogger(AsyncMapperTask.class);
    private TaskBackHandler<T> callback;

    private Object mapper;

    private Method method;

    private T args;

    public AsyncMapperTask(Object mapper, Method method, T args, TaskBackHandler<T> callback) {
        this.mapper = mapper;
        this.method = method;
        this.args = args;
        this.callback = callback;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void run() {
        T result;
        try {
            result = (T) method.invoke(mapper, args);
            callback.taskBack(true, result);
        } catch (Exception e) {
            // 仅仅捕获数据库访问异常
            logger.error("执行数据库查询发生异常", e);
            try {
                callback.taskBack(false, null);
            } catch (Exception e1) {
                e1.printStackTrace();
                logger.error("执行数据库查询发生异常", e1);
            }
        }
    }
}
